<template>
  <div class="community-add">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ formTitle }}</span>
        </div>
      </template>
      <div class="form-container">
        <el-form
          :model="communityForm"
          :rules="rules"
          ref="communityFormRef"
          label-width="120px"
          :disabled="loading"
          v-loading="loading"
        >
          <el-form-item label="小区编号" prop="code">
            <el-input v-model="communityForm.code" placeholder="请输入小区编号"></el-input>
          </el-form-item>
          <el-form-item label="小区名称" prop="name">
            <el-input v-model="communityForm.name" placeholder="请输入小区名称"></el-input>
          </el-form-item>
          <el-form-item label="坐落地址" prop="address">
            <el-input v-model="communityForm.address" placeholder="请输入坐落地址"></el-input>
          </el-form-item>
          <el-form-item label="占地面积(m²)" prop="area">
            <el-input-number v-model="communityForm.area" :min="1" :precision="2"></el-input-number>
          </el-form-item>
          <el-form-item label="总栋数" prop="totalBuildings">
            <el-input-number v-model="communityForm.totalBuildings" :min="1" :precision="0"></el-input-number>
          </el-form-item>
          <el-form-item label="总户数" prop="totalHomes">
            <el-input-number v-model="communityForm.totalHomes" :min="1" :precision="0"></el-input-number>
          </el-form-item>
          <el-form-item label="绿化率(%)" prop="greenRate">
            <el-input-number v-model="communityForm.greenRate" :min="0" :max="100" :precision="2"></el-input-number>
          </el-form-item>
          <el-form-item label="缩略图" prop="thumbnail">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :http-request="handleUpload"
            >
              <img v-if="communityForm.thumbnail" :src="communityForm.thumbnail" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="开发商名称" prop="developerName">
            <el-input v-model="communityForm.developerName" placeholder="请输入开发商名称"></el-input>
          </el-form-item>
          <el-form-item label="物业公司名称" prop="propertyCompany">
            <el-input v-model="communityForm.propertyCompany" placeholder="请输入物业公司名称"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="communityForm.status">
              <el-radio :label="1">显示</el-radio>
              <el-radio :label="0">隐藏</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting">提交</el-button>
            <el-button @click="goBack">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'CommunityAdd',
  components: {
    Plus
  },
  data() {
    return {
      formTitle: '添加小区',
      loading: false,
      submitting: false,
      communityForm: {
        id: null,
        code: '',
        name: '',
        address: '',
        area: 0,
        totalBuildings: 0,
        totalHomes: 0,
        greenRate: 0,
        thumbnail: '',
        developerName: '',
        propertyCompany: '',
        status: 1
      },
      rules: {
        code: [
          { required: true, message: '请输入小区编号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入小区名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入坐落地址', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入占地面积', trigger: 'change' }
        ],
        totalBuildings: [
          { required: true, message: '请输入总栋数', trigger: 'change' }
        ],
        totalHomes: [
          { required: true, message: '请输入总户数', trigger: 'change' }
        ],
        developerName: [
          { required: true, message: '请输入开发商名称', trigger: 'blur' }
        ],
        propertyCompany: [
          { required: true, message: '请输入物业公司名称', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    // 如果是编辑，则获取ID并加载数据
    const id = this.$route.query.id;
    if (id) {
      this.formTitle = '编辑小区';
      this.loadCommunityData(id);
    }
  },
  methods: {
    async loadCommunityData(id) {
      try {
        this.loading = true;
        const response = await axios.get(`/api/communities/${id}`);
        this.communityForm = response.data;
      } catch (error) {
        console.error('Failed to load community data:', error);
        ElMessage.error('加载小区数据失败');
      } finally {
        this.loading = false;
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('上传头像图片只能是图片格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    handleUpload(options) {
      // 模拟上传过程
      const { file } = options;
      // 创建临时URL展示图片
      this.communityForm.thumbnail = URL.createObjectURL(file);
      
      // 实际项目中，这里会调用API上传图片
      ElMessage.success('图片上传成功');
    },
    async submitForm() {
      try {
        await this.$refs.communityFormRef.validate();
        
        this.submitting = true;
        
        if (this.communityForm.id) {
          // 更新小区
          const response = await axios.put(`/api/communities/${this.communityForm.id}`, this.communityForm);
          if (response.data.success) {
            ElMessage.success('编辑成功');
          } else {
            throw new Error(response.data.message || '编辑失败');
          }
        } else {
          // 添加小区
          const response = await axios.post('/api/communities', this.communityForm);
          if (response.data.success) {
            ElMessage.success('添加成功');
          } else {
            throw new Error(response.data.message || '添加失败');
          }
        }
        
        // 返回列表页
        this.goBack();
      } catch (error) {
        console.error('Failed to submit form:', error);
        ElMessage.error(error.response?.data?.message || error.message || '提交失败，请稍后重试');
      } finally {
        this.submitting = false;
      }
    },
    goBack() {
      this.$router.push('/property/community');
    }
  }
};
</script>

<style scoped>
.community-add {
  padding: 20px;
}
.form-container {
  max-width: 800px;
  margin: 0 auto;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
